package cn.edu.njust.balancer;

import cn.edu.njust.server.Server;
import cn.edu.njust.server.Stat;
import lombok.AllArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;

@AllArgsConstructor
public class ServerStatUpdaterProxyHandler implements InvocationHandler {

    private Server server;

    private Stat stat;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("service")) {
            LocalDateTime start = LocalDateTime.now();
            stat.getBacklogAndIncrement();

            Object returnValue = method.invoke(server, args);

            stat.getBacklogAndDecrement();
            stat.setLastLatency(Duration.between(start, LocalDateTime.now()).toMillis());
            return returnValue;
        }

        return method.invoke(server, args);
    }
}
